from locust import HttpUser, task, between
import random, time

class APIUser(HttpUser):
    wait_time = between(0.5, 1)  # 每个虚拟用户两次请求间的“思考时间”

    @task(3)  # 写请求权重更高
    def post_data(self):
        did = random.randint(1, 100)
        payload = {
            "id": did,
            "username": f"user{did}",
            "value": round(random.random() * 100, 4),
            "ts": int(time.time())
        }
        with self.client.post("/api/data", json=payload, catch_response=True) as r:
            if r.status_code != 201:
                r.failure(f"POST {r.status_code} {r.text}")

    @task(1)
    def get_latest(self):
        with self.client.get("/api/latest", name="/api/latest", catch_response=True) as r:
            if r.status_code != 200:
                r.failure(f"GET {r.status_code} {r.text}")
